package com.longrise.android.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Environment;
import android.util.DisplayMetrics;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Util
{
	/**
	 * fuction: 设置固定的宽度，高度随之变化，使图片不会变形
	 *
	 * @param target 需要转化bitmap参数
	 * @param newWidth 设置新的宽度
	 * @return
	 */
	public static Bitmap fitBitmap(Bitmap target, int newWidth)
	{
		int width = target.getWidth();
		int height = target.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) newWidth) / width;
		matrix.postScale(scaleWidth, scaleWidth);
		Bitmap bmp = Bitmap.createBitmap(target, 0, 0, width, height, matrix,true);
		if (target != null && !target.equals(bmp) && !target.isRecycled())
		{
			target.recycle();
			target = null;
		}
		return bmp;
	}

    /**
     *
     * 获取屏幕宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context)
    {
    	if(null == context)
    	{
    		return -1;
    	}
    	DisplayMetrics dm = context.getApplicationContext().getResources()
				.getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     *
     * 获取屏幕的高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context)
    {
    	if(null == context)
    	{
    		return -1;
    	}
    	DisplayMetrics dm = context.getApplicationContext().getResources()
    			.getDisplayMetrics();
    	return dm.heightPixels;
    }

	/**
	 *
	 * 读取文件为字节数组
	 */
	public static String readTextFile(String path)
	{
		if (null == path || "".equals(path))
		{
			return null;
		}
		File file = new File(path);
		if (!file.exists())
		{
			return null;
		}

		InputStream fis = null;
		ByteArrayOutputStream baos = null;
		InputStream is = null;
		try
		{
			baos = new ByteArrayOutputStream();
			fis = new FileInputStream(file);
			is = new BufferedInputStream(fis);
			// 长度
			int count = 0;
			// 一次性读取的字节
			byte[] buf = new byte[1024];
			// 循环读取，以-1为结束标识
			while ((count = is.read(buf)) != -1)
			{
				if (count > 0)
				{
					baos.write(buf, 0, count);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (null != fis)
				{
					fis.close();
				}
				if (null != is)
				{
					is.close();
				}
				if (null != baos)
				{
					baos.close();
				}
			}
			catch (Exception e2)
			{
			}
		}
		return new String(baos.toByteArray());
	}


	/**
	 * 写入文件
	 * @param path
	 * @param data
     */
	public static void writeTextFile(String path,String data)
	{
		if(path == null || path.isEmpty() || data == null)
		{
			return;
		}

		//判断SDCard是否可用
		String sdStatus = Environment.getExternalStorageState();
		if (!(sdStatus.equals(Environment.MEDIA_MOUNTED)))
		{
			return;
		}

		FileOutputStream fileOutputStream = null;

		try {
			File file = new File(path);

			//判断目录是否存在
			if (!file.getParentFile().exists())
			{
				file.getParentFile().mkdirs();
			}
			//判断文件是否存在
			if (file.exists())
			{
				boolean b = file.delete();
				if(!b)
				{
					return;
				}
			}

			boolean success = file.createNewFile();
			if(!success)
			{
				return;
			}

			fileOutputStream = new FileOutputStream(file);
			byte[] bytes = data.getBytes();
			fileOutputStream.write(bytes);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(null != fileOutputStream)
				{
					fileOutputStream.close();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

	}

    /**
	 * PX转成dip
	 *
	 * @param context
	 * @param pxValue
	 * @return
	 */
	public int px2dip(Context context, float pxValue)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	/**
	 * dip转化成px
	 *
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dip2px(Context context, float dipValue)
	{
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	//------------------------------对手机内存的读取删除操作方法----------------------------------
	/**
	 * 写入到手机内存中
	 * @param fileName
	 * 			文件名
	 * @param content
	 * 			写入的内容
	 * @param context
	 * 			上下文对象
	 * @return
	 * 			返回是否写入成功
	 */
	public static boolean write(String fileName,String content,Context context)
	{
		if(null == fileName || "".equals(fileName) || null == content || "".equals(content) || null == context)
		{
			return false;
		}
		boolean b = true;
		FileOutputStream fileOut = null;
        try
        {
            // 以追加的方式打开文件输出流  
            fileOut = context.openFileOutput(fileName,Activity.MODE_APPEND);
            // 写入数据  
            fileOut.write(content.getBytes());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
        	 // 关闭文件输出流
            try
            {
            	if(null != fileOut)
            	{
            		fileOut.close();
            	}
            	fileOut = null;
			}
            catch (Exception e)
			{
				e.printStackTrace();
				b = false;
			}
        }
        return b;
    }

	/**
	 * 读取手机内存的文件
	 * @param fileName
	 * 			文件名
	 * @param context
	 * 			上下文对象
	 * @return
	 * 			返回读取的内容
	 */
    public static String read(String fileName,Context context)
    {
    	String txt = null;
    	FileInputStream fileInput = null;
    	BufferedReader br = null;
    	if(null == fileName || "".equals(fileName) || null == context)
    	{
    		return txt;
    	}
        try
        {
            // 打开文件输入流  
            fileInput = context.openFileInput(fileName);
            br = new BufferedReader(new InputStreamReader(fileInput));
            String str = null;
            StringBuilder stb = new StringBuilder();
            while ((str = br.readLine()) !=null )
            {
                stb.append(str);
            }
            str = null;
            txt = stb.toString();
            stb = null;

        }
        catch (Exception e)
        {
            e.printStackTrace();
            txt = null;
        }
        finally
        {
        	try
        	{
				if(null != fileInput)
				{
					fileInput.close();
				}
				fileInput = null;

				if(null != br)
				{
					br.close();
				}
				br = null;
			}
        	catch (Exception e2)
			{
			}
        }

        return txt;
    }
}
